//index.js
//获取应用实例
const app = getApp()
const bleSender = require('../../utils/bleSender.js')
import {ab2hex,inArray,byteToString} from "../../utils/util"
import {genearteData,getServiceUUIDs} from "../../utils/BLEUtil"

Page({
  timer:null,
  system:'android',
  data: {
    _discoveryStarted:false,
    advertiseStart: false,
    discoveryReady:false,
    advertiseReady:false,
    payload:'',
    devices: [
    ],
    scanResult:'',
    servers: [],
    serverId: '',
    lanyaState:false,
    refuState:false,
    num:8,
    dianciNum:3,
    dianchiState:true,
    dotAnData: {},
    timeMsg:'15',
    dotAnFun:null,
    functionList: [
      { name: '循环', icon: '../../images/xunhuan1.png', icon_active: '../../images/xunhuan3.png',num:'01'},
      { name: '揉捏', icon: '../../images/rounie1.png', icon_active: '../../images/rounie3.png', num: '02'},
      { name: '刮痧', icon: '../../images/guasha1.png', icon_active: '../../images/guasha3.png', num: '04'},
      { name: '针灸', icon: '../../images/zhenjiu1.png', icon_active: '../../images/zhenjiu3.png', num: '08'},
      { name: '敲打', icon: '../../images/qiaoda1.png', icon_active: '../../images/qiaoda3.png', num: '10'},
    ],
    curFunctionIndex:0,
    ramNumber: '0000',
    numTwo: '00',
    checkCode: '',
    startState:true,
    yinState:false,
    switchChecked:false,
    setIntervalBlock:null,
    showNoneBill:false,
    lanyaList:[],
    animationData:null
  },

  gotoConfig(){
    wx.navigateTo({
      url: '/pages/config/config',
    })
  },

  onLoad(){
    wx.setStorageSync('address', 'cccccccccc')
    wx.setStorageSync('channel', '37')
    this.initSystemInfo()
    this.initPayload();
    this.initAdvertiseAdapter()
    this.initDiscoveryAdapter()
  },
  onUnload() {
    clearInterval(this.data.dotAnFun);
    clearInterval(this.data.setIntervalBlock);
    this.stopAdvertising()
    this.data.servers.forEach(server => {
      server.close()
    })
  },
  onHide() {
    clearInterval(this.data.setIntervalBlock);
    clearInterval(this.data.dotAnFun);
  },
  gotoAttention() {
    wx.navigateTo({
      url: '/pages/attention_page/index',
    })
  },
  clickShowNoPay: function () {
    let that = this;
    let showNoneBill;
    if (that.data.showNoneBill) {
      showNoneBill = false
    } else {
      showNoneBill = true
    }
    that.setData({ showNoneBill: showNoneBill })
    let animation = wx.createAnimation({
      duration: 400,
      timingFunction: 'ease-in-out',
    })
    if (showNoneBill) {
      animation.height(250).step()
    } else {
      animation.height(0).step()
    }
    this.setData({
      animationData: animation.export()
    })
  },
  closeZhezhao: function () {
    this.setData({ showTypeTwo: false })
    let animation = wx.createAnimation({
      duration: 400,
      timingFunction: 'ease-out',
    })
    animation.height(0).step()
    let setData = animation.export()
    this.setData({
      animationDataTwo: setData
    })
  },
  // getRamNumber:function (){
  //   var result = '';
  //   for(var i = 0; i<4; i++){
  //     result += Math.floor(Math.random() * 16).toString(16);//获取0-15并通过toString转16进制
  //   }
  //   console.log("====result=====", result)
  //   //默认字母小写，手动转大写
  //   this.setData({ 
  //     ramNumber: result
  //   })
  //   return result.toUpperCase();//另toLowerCase()转小写
  // },
  // closeFun:function(){
  //   if (this.data.ramNumber){
  //     let checkCode = this.getCheckCodeFun('01', '00')
  //     console.log("checkCode", checkCode)
  //     this.setData({
  //       payload: this.data.ramNumber + this.data.numTwo + '0100' + checkCode
  //     })
  //   }else{

  //   }
  // },
  // openFun: function () {
  //   if (this.data.ramNumber) {
  //     let checkCode = this.getCheckCodeFun('01','01')
  //     console.log("checkCode", checkCode)
  //     this.setData({
  //       payload: this.data.ramNumber + this.data.numTwo + '0101' + checkCode
  //     })
  //   } else {

  //   }
  // },
  // getCheckCodeFun: function (num1, num2) {
  //   console.log('====5====')
  //   if (this.data.ramNumber) {
  //     console.log("===getCheckCodeFun===", parseInt(this.data.ramNumber.slice(0, 2), 16), parseInt(this.data.ramNumber.slice(2), 16))
  //     let checkCode = (parseInt(this.data.ramNumber.slice(0, 2), 16) + parseInt(this.data.ramNumber.slice(2), 16) + parseInt(this.data.numTwo, 16) + parseInt(num1, 16) + parseInt(num2, 16)).toString(16).slice(-2)
  //     console.log("checkCode", checkCode);
  //     this.setData({
  //       checkCode: checkCode
  //     })
  //     return checkCode
  //   }
  // },
  // funFun:function(e){
  //   console.log("===funFun===",e);
  //   let num = e.currentTarget.dataset.num;
  //   let typeNum = e.currentTarget.dataset.typenum;
  //   let checkCode = this.getCheckCodeFun(typeNum, num)
  //   this.setData({
  //     payload: this.data.ramNumber + this.data.numTwo + typeNum + num + checkCode
  //   })
  // },
  // 指令发送start
  getRamNumber: function () {
    var result = '';
    for (var i = 0; i < 4; i++) {
      result += Math.floor(Math.random() * 16).toString(16);//获取0-15并通过toString转16进制
    }
    console.log("====result=====", result)
    //默认字母小写，手动转大写
    this.setData({
      ramNumber: result
    })
    return result.toUpperCase();//另toLowerCase()转小写
  },
  // closeFun: function () {
  //   if (this.data.ramNumber) {
  //     let checkCode = this.getCheckCodeFun('01', '00')
  //     console.log("checkCode", checkCode)
  //     this.setData({
  //       payload: this.data.ramNumber + this.data.numTwo + '0100' + checkCode
  //     })
  //   } else {

  //   }
  // },
  // openFun: function () {
  //   if (this.data.ramNumber) {
  //     let checkCode = this.getCheckCodeFun('01', '01')
  //     console.log("checkCode", checkCode)
  //     this.setData({
  //       payload: this.data.ramNumber + this.data.numTwo + '0101' + checkCode
  //     })
  //   } else {

  //   }
  // },
  getCheckCodeFun: function (num1, num2) {
    if (this.data.ramNumber) {
      console.log("===getCheckCodeFun===", parseInt(this.data.ramNumber.slice(0, 2), 16), parseInt(this.data.ramNumber.slice(2), 16))
      let checkCode = (parseInt(this.data.ramNumber.slice(0, 2), 16) + parseInt(this.data.ramNumber.slice(2), 16) + parseInt(this.data.numTwo, 16) + parseInt(num1, 16) + parseInt(num2, 16)).toString(16).slice(-2)
      console.log("checkCode", checkCode);
      let checkCodeOne = parseInt(checkCode, 16);
      console.log("===checkCodeOne====", checkCodeOne)
      checkCode = checkCodeOne < 16 ? (checkCode.length == 2 ? checkCode : "0" + checkCode) : checkCode;
      console.log("===checkCode===", checkCode)
      this.setData({
        checkCode: checkCode
      })
      return checkCode
    }
  },
  funFun: function (e) {
    console.log("===funFun===", e);
    let that=this;
    let num = e.currentTarget ? e.currentTarget.dataset.num : e.num;
    let typeNum = e.currentTarget ? e.currentTarget.dataset.typenum : e.typeNum;
    let checkCode = that.getCheckCodeFun(typeNum, num)
    let foundLanya = (e.currentTarget ? e.currentTarget.dataset.foundlanya : e.foundLanya)||false;
    if (this.data.ramNumber == '0000' && typeNum!='0b') {
      wx.showToast({
        title: '您还未连接',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    that.setData({
      payload: that.data.ramNumber + that.data.numTwo + typeNum + num + checkCode
    })
    // clearInterval(that.data.setIntervalBlock);
    // that.setData({ setIntervalBlock:null})
    that.startSendAndDiscovery(typeNum, foundLanya)
  },
  // 指令发送end
  startFun: function (e) {
    let that = this;
    let type = e.currentTarget.dataset.type;
    console.log("==startFun===", e, type)
    console.log("====startFun====1", that.data.dotAnData)
    console.log("====startFun====2", that.data.dotAnData)
    if (type == 'stop') {
      let param = {
        typeNum: '01',
        num: '01'
      }
      that.funFun(param)
      // clearInterval(that.data.dotAnFun);
      that.setData({
        // dotAnData: null,
        startState: false,
      });
    } else {
      let param = {
        typeNum: '01',
        num: '02'
      }
      this.funFun(param)
      // var dotAnData = wx.createAnimation({
      //   duration: 1000,
      //   transformOrigin: '300rpx 27rpx'
      // })
      // dotAnData.rotate(0).step();
      that.setData({
        // dotAnData: dotAnData.export(),
        startState: true,
      })
      // that.startTimeFun()
    }
    // console.log("====startAgainFun====3", dotAnData)

  },
  // 指令发送end
  startAgainFun: function (e) {
    let that = this;
    let type = e.currentTarget.dataset.type;
    console.log("==startAgainFun===", e, type)
      let param = {
        typeNum: '04',
        num: '0f'
      }
      this.funFun(param)
      that.setData({
        startState: true,
      })
  },
  // startTimeFun: function () {
  //   let that = this;
  //   var i = 0;
  //   let time=15*60;
  //   let msg;
  //   var dotAnData = wx.createAnimation({
  //     duration: 1000,
  //     transformOrigin: '300rpx 27rpx'
  //   })
  //   clearInterval(that.data.dotAnFun);
  //   that.setData({ dotAnFun: null });
  //   that.setData({
  //     dotAnFun: setInterval(function () {
  //       let num = 0.2 * (++i);
  //       dotAnData.rotate(num).step({ duration:1000});
  //       console.log("=====uuu=====", num,i);
  //       if (time < 0) {
  //         clearInterval(that.data.dotAnFun);
  //         that.setData({ dotAnFun: null });
  //         return
  //       } else {
  //         let minutes = Math.floor(time / 60);
  //         let seconds = Math.floor(time % 60);
  //         msg = minutes + ":" + (seconds >= 10 ? seconds : '0' + seconds);
  //         --time;
  //       }
  //       that.setData({
  //         dotAnData: dotAnData.export(),
  //         timeMsg: msg
  //       })

  //     }.bind(that), 1000)
  //   })

  // },
  selectFunctionFun:function(e){
    console.log("selectFunctionFun",e);
    let functionList = this.data.functionList
    let index = e.currentTarget?e.currentTarget.dataset.index:e.index||'for';
    let typeNum = e.currentTarget ? e.currentTarget.dataset.typenum : e.typenum;
    let num = e.currentTarget ? e.currentTarget.dataset.num : e.num;
    let param = {
      typeNum: typeNum,
      num: num
    }
    if (index == 'for') {
      for (let i = 0; i < functionList.length;i++){
        if (functionList[i].num == num){
          this.setData({ curFunctionIndex: i });
        }
      }
    } else {
      this.setData({ curFunctionIndex: index });
      this.funFun(param)
    }
    
  },
  openLanyaFun:function(e){
    let typeNum = e.currentTarget.dataset.typenum;
    let type = e.currentTarget.dataset.type;
    console.log("===type===", type)
    if (type == 'a') {
      let param = {
        typeNum: typeNum,
        num: '00',
        foundLanya:true,
      }
      this.funFun(param)
    }else{
      clearInterval(this.data.setIntervalBlock);
      this.setData({ lanyaState: !this.data.lanyaState, ramNumber: '0000' });
    }
  },
  openRefuFun: function (e) {
    let refuState= this.data.refuState;
    let state = e.detail.value
    this.setData({ refuState: state });
    let typeNum = e.currentTarget.dataset.typenum;
    let param = {
      typeNum: typeNum,
      num: state?'01':'02'
    }
    this.funFun(param)
  },
  openYinpinfuFun: function (e) {
    let yinState = this.data.yinState
    this.setData({ yinState: !this.data.yinState });
    let typeNum = e.currentTarget.dataset.typenum;
    let param = {
      typeNum: typeNum,
      num: !yinState ? '01' : '02'
    }
    this.funFun(param)
  },
  controlBarFun:function(e){
    console.log("==controlBarFun===", e);
    let type = e.currentTarget ? e.currentTarget.dataset.type : e.type;
    let typeNum = e.currentTarget ? e.currentTarget.dataset.typenum : e.typenum;
    let initNum = e.currentTarget ? e.currentTarget.dataset.num : e.num;
    let num = Number(this.data.num.toFixed(1));
    console.log(", this.data.num", this.data.num, num, initNum)
    if (type =='add'){
      if (num<91.2){
        let toFixedNum = Number((num + 6.4).toFixed(1))
        this.setData({ num: toFixedNum})
        num = toFixedNum
      } else if (num == 91.2) {
        let toFixedNum = Number((num + 8.8).toFixed(1))
        this.setData({ num: toFixedNum })
        num = toFixedNum
      }else{
        wx.showToast({
          title: '已经最大啦！',
          icon: 'none',
          duration: 2000
        })
      }
      console.log("num+", num, this.data.num)
    } else if (type == 'minus'){
      if (num == 100) {
        let toFixedNum = Number((num - 8.8).toFixed(1))
        this.setData({ num: toFixedNum})
        num = toFixedNum
      } else if (num <= 91.2 && num != 8) {
        let toFixedNum = Number((num - 6.4).toFixed(1))
        this.setData({ num: toFixedNum })
        num = toFixedNum
      } else if (num ==8) {
        wx.showToast({
          title: '已经最小啦！',
          icon: 'none',
          duration: 2000
        })
      }
      console.log("num-", num, this.data.num)
    }else{
      if (initNum < 15 && initNum>1){
        num = (initNum-1) * 6.4+8
      } else if (initNum==15){
        num=100
      }else{
        num = 8
      }
      this.setData({ num: num})
    }
    let realNum = 0
    if (num <= 91.2){
      realNum = Math.ceil((num - 8) / 6.4)+1;
    }else{
      realNum = Math.ceil((num - 8.8) / 6.4);
    }
    console.log("==realNum.toString(16)===", realNum,realNum.toString(16))
    num = realNum.toString(16).length == 2 ? realNum.toString(16): '0' + realNum.toString(16);
    // num = realNum.toString(16) < 16 ? "0" + checkCode : checkCode;
    let param={
      typeNum: typeNum,
      num: num
    }
    console.log("===param====", param)
    if (type!='init'){
     this.funFun(param)
   }
  },
  initSystemInfo(){
    const {system} = wx.getSystemInfoSync();
    console.log('system',system)
    this.system = system
  },
  initPayload(){
    wx.getStorage({
      key: 'payload',
      success:(res)=>{
        if(res.data){
          this.setData({payload:res.data})
        }
      }
    })
  },
  onPayloadChange(e){
    const payload = e.detail .value
    // console.log('payload',payload)
    this.setData({payload})
  },
  abc:function(){
    let param={
          typeNum:'0a',
          num:'00'
        }
        this.funFun(param)
  },
  xintiaoFun:function(text){
    let that = this;
    console.log("===xintiaoFun==", text)
    // if (that.data.ramNumber != '0000') {
    //   console.log("==that.data.ramNumber===", that.data.ramNumber)
    //   let param = {
    //     typeNum: '0a',
    //     num: '00'
    //   }
    //   that.funFun(param)
    // }
    that.data.setIntervalBlock = setInterval(
      function () {
        console.log("===1===")
        if (that.data.ramNumber != '0000') {
          console.log("==that.data.ramNumber===", that.data.ramNumber)
          let param = {
            typeNum: '0a',
            num: '00'
          }
          that.funFun(param)
        }
      }, 5000)
    that.setData({
      setIntervalBlock: that.data.setIntervalBlock
    })
  },
  initDataFun:function(data){
    console.log("===initDataFun===",data);
    let that=this;
    var bbb = [...data];
    var ccc = data.split('');
    var a, b;
    var aIndex = 0;
    var bIndex = 1;
    var arr = [];

    bbb.forEach((str, index) => {
      if (index % 2 === 0) {
        a = str;
        aIndex += 1
        console.log('a,aIndex', a, aIndex)

      } else {
        b = str
        bIndex += 1
        console.log('b,bIndex', b, bIndex)
      }
      if (a && b && (bIndex - aIndex === 1)) {
        arr.push(a + b)
      }
    });
    that.setData({
      startState: arr[0] == '02' ? true : false,
      timeMsg: parseInt(arr[3], 16),
      refuState: arr[4] == '01' ? true : false,
      dianchiState: arr[5] == '00' ? true : false,
      yinState: arr[6] == '01' ? true : false,
    })
    that.selectFunctionFun({ num: arr[1], typnum:'02'});
    console.log("===parseInt(arr[2], 16)===", arr[2], parseInt(arr[2], 16))
    that.controlBarFun({ typenum: '03', type: 'init', num: parseInt(arr[2], 16)})
  },
  initDiscoveryAdapter(){
    let that=this;
    wx.openBluetoothAdapter({
      // mode: 'peripheral',
      success: (res) => {
        console.log('initDiscoveryAdapter success', res)
        this.setData({ lanyaState: true })
        // this.getRamNumber()
        this.initBluetoothDevicesDiscovery();
        that.xintiaoFun('初始化心跳');
      },
      fail: (res) => {
        console.log("initDiscoveryAdapter ble unavailable!",res);
        this.setData({ lanyaState:false})
        wx.showModal({
          content:'蓝牙初始化失败',
          cancelColor: 'cancelColor',
        })
      }
    })
  },
  initAdvertiseAdapter(){
    wx.openBluetoothAdapter({
      mode: 'peripheral',
      success: (res) => {
        console.log('initAdvertiseAdapter success', res)
        this.createBLEPeripheralServer()
      },
      fail: (res) => {
        console.log("initAdvertiseAdapter ble unavailable!",res)
      }
    })
  },
  
  startSendAndDiscovery(numType, foundLanya){
    let payload = this.data.payload
    payload = payload.replace(/\s+/g,'')
    if(!payload || payload.length === 0){
      wx.showModal({
        content:'请填写payload',
        cancelColor: 'cancelColor',
      })
      return
    }
    wx.setStorage({
      data: payload,
      key: 'payload',
    })
    if(!this.data.discoveryReady ){
      wx.showModal({
        content:'初始化未成功',
        cancelColor: 'cancelColor',
      })
      console.log('接收初始化失败')
      this.initDiscoveryAdapter()
      return
    }

    if(!this.data.advertiseReady){
      wx.showModal({
        content:'初始化未成功',
        cancelColor: 'cancelColor',
      })
      console.log('发送初始化失败')
      this.initAdvertiseAdapter()
    }
    this.setData({scanResult:''})
    setTimeout(() => {
      this.startBluetoothDevicesDiscovery(numType, foundLanya) 
    }, 100);
    const actPayload = genearteData(payload);
    this.startAdvertising(actPayload)
  },
initBluetoothDevicesDiscovery(){
  if (this.data._discoveryStarted) {
    return
  }
  if(!this.data._discoveryStarted){
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      powerLevel: "high",
      // services: ['11:22:33:44:55:66'],
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery success! ', res)
        this.setData({discoveryReady:true})
      },
      fail:(res)=>{
        console.log('startBluetoothDevicesDiscovery failed! ', res)
      }
    })
  }
},
  
  startBluetoothDevicesDiscovery(numType, foundLanya) {
    if(this.data._discoveryStarted)
      return
      this.onBluetoothDeviceFound(numType, foundLanya)
      console.log("===start disvocerry===");
      this.setData({"_discoveryStarted":true})

  },
  stopBluetoothDevicesDiscovery() {
    if(!this.data._discoveryStarted)
      return
    this.setData({"_discoveryStarted":false})
    wx.offBluetoothDeviceFound()
  },
  onBluetoothDeviceFound(numType, foundLanya) {
    console.log('======onBluetoothDeviceFound start=====', foundLanya)
    let lanyaList = [];
    wx.onBluetoothDeviceFound((res) => {
      // console.log('======onBluetoothDeviceFound1=====', res)
      res.devices.forEach(device => {
        if (!device.name ||  !device.localName  || device.name != 'TEMP' ) {
          return
        }
         console.log('device',device)
        const foundDevices = this.data.lanyaList
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {};
        let hexData = ab2hex(device.advertisData)
        let ramNumber = hexData.substring(0, 4);
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device;
          let paramItem = Object.assign({}, device, { ramNumber: ramNumber})
          lanyaList.push(paramItem);
        } else {
          data[`devices[${idx}]`] = device
        }
        this.setData({ lanyaList: lanyaList})
        console.log("===ramNumber===", ramNumber, this.data.lanyaList)
        hexData = hexData.substring(4)
        // if (this.data.ramNumber=='0000'){
        //   this.setData({
        //     ramNumber: ramNumber
        //   })
        // }else{
        //   this.xintiaoFun('操作后重开心跳');
        // }
        if (!foundLanya) {
          // this.xintiaoFun('操作后重开心跳');
          if (numType == '0a') {
            console.log("心跳保存", numType, hexData)
            this.initDataFun(hexData)
          }
        }
        this.setData({"_discoveryStarted":false})
        device.data = hexData
        this.stopAdvertising();
        this.setData({scanResult:device.data})
      })
    })
    if (foundLanya){
      this.clickShowNoPay()
    }
    // this.setData({ lanyaList: lanyaList });
  },
  confirmLanyaFun:function(e){
    console.log("==confirmLanyaFun===");
    this.clickShowNoPay()
    let ramNumber = e.currentTarget.dataset.ramnumber;
    this.setData({
      ramNumber: ramNumber
    })
  },
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter()
    this.setData({"_discoveryStarted":false})
  },
  createBLEPeripheralServer() {
    wx.createBLEPeripheralServer().then(res => {
      console.log('createBLEPeripheralServer', res)
      this.data.servers.push(res.server)
      this.server = res.server
      this.setData({ advertiseReady:true,serverId: this.server.serverId })
    })
  },
  closeServer() {
    this.server.close()
  },
 
  startAdvertising(actPayload) {
    const isIos = this.system.indexOf('iOS') >= 0
    const isIos13 = isIos && this.system.indexOf('13.') >= 0

    const uuids = getServiceUUIDs(actPayload,isIos13)
    this.server.startAdvertising({
      advertiseRequest: {
        connectable: true,
        deviceName: isIos?'11':'',
        serviceUuids:isIos?uuids:[],
        manufacturerData:isIos?[]:[ {
          manufacturerId: '0x00C7',
          manufacturerSpecificData: actPayload,
        }]
      },
      powerLevel: 'high'
    }).then(res => {
      console.log('startAdvertising', res)
      this.setData({ advertiseStart: true })
      this.stopTimer();
      this.timer = setTimeout(()=>{
        this.stopAdvertising()
      },30000)
    }, res => {
      this.setData({ advertiseStart: false })
      console.log("fail: ", res)
    })
  },
  stopTimer(){
    if(this.timer){
      clearTimeout(this.timer)
      this.time = null
    }
  },


  stopAdvertising() {
    this.stopTimer();
    this.stopBluetoothDevicesDiscovery()
   
    if (this.server) {
      this.server.stopAdvertising()
      this.setData({ advertiseStart: false })
    }
  
  },
})
